package com.cake.liulanxiangzhu.controller;

import com.cake.liulanxiangzhu.exception.ServiceException;
import com.cake.liulanxiangzhu.pojo.entity.OmsOrder;
import com.cake.liulanxiangzhu.pojo.entity.OmsOrderItem;
import com.cake.liulanxiangzhu.pojo.vo.OmsOrderVO;
import com.cake.liulanxiangzhu.service.OmsOrderItemService;
import com.cake.liulanxiangzhu.service.OmsOrderService;
import com.cake.liulanxiangzhu.utils.ExcelUtils;
import com.cake.liulanxiangzhu.web.JsonResult;
import com.cake.liulanxiangzhu.web.ServiceCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/excel")
public class ExcelController {

    @Autowired
    private OmsOrderService omsOrderService;

    @Autowired
    private OmsOrderItemService omsOrderItemService;

    @GetMapping("/toExport")
    public void exportConsumList() {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getResponse();
        List<OmsOrderVO> omsOrderVOS = omsOrderService.queryAllOrderExport();
        ExcelUtils.writeExcel(response, omsOrderVOS, OmsOrderVO.class, "订单数据.xlsx");

    }

    @PostMapping("/readExcel")
    public JsonResult<Void> readExcel(@RequestParam(value = "file", required = false) MultipartFile file) {
        if (file != null) {
            List<OmsOrderVO> omsOrderVOS = ExcelUtils.readExcel("", OmsOrderVO.class, file);
            List<OmsOrder> orders = new ArrayList<>();
            List<OmsOrderItem> items = new ArrayList<>();
            for (OmsOrderVO omsOrderVO : omsOrderVOS) {
                OmsOrder omsOrder = new OmsOrder();
                omsOrder.setSn(omsOrderVO.getSn());
                omsOrder.setUserId(omsOrderVO.getUserId());
                omsOrder.setUserName(omsOrderVO.getUserName());
                omsOrder.setUserTelephone(omsOrderVO.getUserTelephone());
                orders.add(omsOrder);

                OmsOrderItem item = new OmsOrderItem();
                item.setOrderId(Integer.parseInt(omsOrderVO.getOrderId()));
                item.setSkuId(omsOrderVO.getSkuId());
                item.setTitle(omsOrderVO.getTitle());
                item.setQuantity(omsOrderVO.getQuantity());
                items.add(item);
            }
            omsOrderService.insertBatch( orders);
            omsOrderItemService.insertBatch(items);
            return JsonResult.ok();
        } else {
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST, "格式异常");
        }
    }

}
